﻿using Microsoft.AspNetCore.Http;
using SageKing.OpenIddict.UI.Infrastructure.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SageKing.OpenIddict.Middlewares;

public class TenantMiddleware
{
    private readonly RequestDelegate _next;

    public TenantMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context, AppDbContext db)
    {
        // 从请求中解析租户ID（示例：从域名或Header获取）
        var tenantId = GetTenantIdFromRequest(context);

        // 设置当前请求的租户ID
        db.SetTenantId(tenantId);

        await _next(context);
    }

    private string GetTenantIdFromRequest(HttpContext ctx)
    {
        var tenantId = ctx.User.FindFirst("TenantId")?.Value;
        return tenantId;
    }
}
